
package com.yimixian.app.user;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.R;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.KV;
import com.yimixian.app.model.User;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.ui.CircleImageView;
import com.yimixian.app.ui.Listener.DialogNormalListener;
import com.yimixian.app.ui.ProgressDialogFragment;
import com.yimixian.app.ui.dialog.MyNormalDialog;
import com.yimixian.app.ui.dialog.WheelViewDialog;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息更改
 */
public class UserInfoEditFragment extends Fragment implements View.OnClickListener {

    @InjectView(R.id.edit_view)
    UserInfoEditView mUserInfoEditView;
    UserInfoEditViewItem headView, nickView, sexView, ageView, careerView, registPhoneView,
            registTimeView;
    List<UserInfoEditViewItem> listViews;
    /** 显示的年龄 */
    KV kv_age = new KV();
    /** 年龄数组 */
    List<KV> timeType_age;
    /** 显示的职业 */
    KV kv_career = new KV();
    private YmxDataService mYmxDataService;
    private DataManager mDataManager;
    private ProgressDialogFragment mProgressDialog;

    User user_local;
    User user;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_userinfo_edit, null);
        mYmxDataService = YmxDataService.getInstance();
        mDataManager = DataManager.getInstance();
        ButterKnife.inject(this, view);
        intitView();
        return view;
    }

    private void intitView() {
        listViews = new ArrayList<>();
        headView = new UserInfoEditViewItem(getActivity());
        headView.setStandardViews(R.string.personal_center_head, false, true);
        headView.getImgHead();
        headView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updata(UserInfoEditView.HEAD_INDEX);
            }
        });
        headView.setClickable(false);
        listViews.add(headView);

        nickView = new UserInfoEditViewItem(getActivity());
        nickView.setStandardViews(R.string.personal_center_nick, true, true);
        nickView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updata(UserInfoEditView.NICK_INDEX);
            }
        });
        listViews.add(nickView);

        sexView = new UserInfoEditViewItem(getActivity());
        sexView.setStandardViews(R.string.personal_center_sex, true, true);
        sexView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updata(UserInfoEditView.SEX_INDEX);
            }
        });
        listViews.add(sexView);

        ageView = new UserInfoEditViewItem(getActivity());
        ageView.setStandardViews(R.string.personal_center_age, true, true);
        ageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updata(UserInfoEditView.AGE_INDEX);
            }
        });
        listViews.add(ageView);

        careerView = new UserInfoEditViewItem(getActivity());
        careerView.setStandardViews(R.string.personal_center_career, true, false);
        careerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updata(UserInfoEditView.CAREER_INDEX);
            }
        });
        listViews.add(careerView);

        registPhoneView = new UserInfoEditViewItem(getActivity());
        registPhoneView.setStandardViews(R.string.personal_center_registphone, false, true);
        registPhoneView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updata(UserInfoEditView.REGISTPHONE_INDEX);
            }
        });
        registPhoneView.setClickable(false);
        listViews.add(registPhoneView);

        registTimeView = new UserInfoEditViewItem(getActivity());
        registTimeView.setStandardViews(R.string.personal_center_registtime, false, false);
        registTimeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updata(UserInfoEditView.REGISTTIME_INDEX);
            }
        });
        registTimeView.setClickable(false);
        listViews.add(registTimeView);
        mUserInfoEditView.setDate(listViews);
    }

    public void initData() {
        user_local = DataManager.getInstance().get(CacheKeys.CURRENT_USER);
        if (user_local == null) return;
        initUser();
        nickView.tvRight.setText(StringUtils.isEmpty(user_local.nickName) ? ""
                : user_local.nickName);
        if (user_local.sex == 0) {// 默认
//            headView.getImgHead().setImageResource(R.drawable.ic_my_head_pic);
            sexView.setTvRight("未知");
        } else if (user_local.sex == 1) {// 男
//            headView.getImgHead().setImageResource(R.drawable.ic_my_head_pic);
            sexView.setTvRight("男");
        } else {// 女
//            headView.getImgHead().setImageResource(R.drawable.ic_my_head_pic);
            sexView.setTvRight("女");
        }
        ageView.setTvRight(String.valueOf(user_local.age));
        if (user_local.career != null) {
            List<KV> careerMap = user.careerMap;
            for (KV kv : careerMap) {
                if (kv.key.equals(user_local.career)) {
                    careerView.setTvRight(kv.value);
                    break;
                }
            }
        }
        registPhoneView.setTvRight(StringUtils.isEmpty(user_local.tel) ? "" : user_local.tel);
        registTimeView.setTvRight(StringUtils.isEmpty(
                user_local.registeringTimestamp) ? "" : user_local.registeringTimestamp);
        final CircleImageView headImageView = headView.getImgHead();
        if(user_local != null && !Strings.isNullOrEmpty(user_local.head_img)){
            Picasso.with(getActivity()).load(user_local.head_img).placeholder(R.drawable.ic_boylhead_selected).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    headImageView.setImageBitmap(bitmap);
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                }
            });
        }
    }

    void updata(int index) {
        switch (index) {
            case UserInfoEditView.HEAD_INDEX:
                break;
            case UserInfoEditView.NICK_INDEX:
                EditNickActivity.buildIntent(getActivity(), null);
                break;
            case UserInfoEditView.SEX_INDEX:
                initUser();
                MyNormalDialog myNormalDialog = new MyNormalDialog(getActivity());
                myNormalDialog.isHintTwoBtnLin(true, 0, 0, R.string.confirm);
                myNormalDialog.setShowSelectBtn(user.sex);
                myNormalDialog.setListener(new DialogNormalListener() {
                    @Override
                    public void onLeftListener() {
                    }

                    @Override
                    public void onRightListener() {
                    }

                    @Override
                    public void onCenterListener() {
                    }

                    @Override
                    public void onCenterListener(int sex) {
                        user.sex = sex;
                        updateUserInfo();
                    }
                });
//                myNormalDialog.show();
                UiUtils.showAlertDialog(myNormalDialog);
                break;
            case UserInfoEditView.AGE_INDEX:
                initUser();
                kv_age.key = String.valueOf(user.age);
                kv_age.value = String.valueOf(user.age);
                if (timeType_age == null) {
                    timeType_age = new ArrayList<>();
                    for (int i = 1; i <= 100; i++) {
                        KV kv = new KV();
                        kv.key = "" + i;
                        kv.value = "" + i;
                        timeType_age.add(kv);
                    }
                }
                WheelViewDialog wheelViewDialog_age = new WheelViewDialog(getActivity(),
                        timeType_age, kv_age);
                wheelViewDialog_age.setmClickSureListener(new WheelViewDialog.ClickSureListener() {
                    @Override
                    public void onConfirm(KV kv) {
                        user.age = Integer.parseInt(kv.value);
                        updateUserInfo();
                    }

                    @Override
                    public void onTwoSelectConfirm(String province, String city) {

                    }
                });
                wheelViewDialog_age.show();
                break;
            case UserInfoEditView.CAREER_INDEX:
                initUser();
                if (user.careerMap == null || user.careerMap.size() <= 0)
                    return;
                for (KV careerKv : user.careerMap) {
                    if (careerKv.key.equals(user.career)) {
                        user.careerCode = careerKv.key;
                        kv_career.value = careerKv.value;
                        break;
                    }
                }
                WheelViewDialog wheelViewDialog_career = new WheelViewDialog(getActivity(),
                        user.careerMap, kv_career);
                wheelViewDialog_career
                        .setmClickSureListener(new WheelViewDialog.ClickSureListener() {
                            @Override
                            public void onConfirm(KV kv) {
                                user.careerCode = kv.key;
                                updateUserInfo();
                            }

                            @Override
                            public void onTwoSelectConfirm(String province, String city) {

                            }
                        });
                wheelViewDialog_career.show();
                break;
            case UserInfoEditView.REGISTPHONE_INDEX:
                break;
            case UserInfoEditView.REGISTTIME_INDEX:
                break;

        }
    }

    @Override
    public void onStart() {
        super.onStart();
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onClick(View view) {
    }

    /**
     * 初始化修改的用户信息
     */
    public void initUser() {
        if (user == null)
            user = new User();
        if (user_local == null)
            return;
        user.sex = user_local.sex;
        user.nickName = user_local.nickName;
        user.careerMap = user_local.careerMap;
        user.career = user_local.career;
        user.age = user_local.age;
        user.head_img = user_local.head_img;
    }

    /**
     * 更新用户信息
     */
    public void updateUserInfo() {
        mProgressDialog = UiUtils.showProgressDialog(getActivity(), "请稍后...", true);
        mYmxDataService.updateUserInfo(user).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Action1<User>() {
                    @Override
                    public void call(User user) {
                        if (user == null)
                            return;
                        mDataManager.put(CacheKeys.CURRENT_USER, user);
                        UiUtils.dismiss(mProgressDialog);
                        initData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        initData();
                        UiUtils.dismiss(mProgressDialog);
                        UiUtils.toastError(getActivity(), throwable);
                    }
                });
    }

}
